<?php
/**
 * Created by PhpStorm.
 * User: as
 * Date: 2018/10/17
 * Time: 0:23
 */

namespace app\api\controller;


use app\api\model\User;
use app\api\model\UserShop;
use app\common\controller\ReturnCode;
use think\Config;
use think\Controller;
use think\Request;
use WeiXinLogin\WXBizDataCrypt;

class Index extends Controller
{
    //授权登陆
    function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this -> weixin = Config::get('weixin');
//        $this -> appid = $this ->weixin['appid'];
////        $this -> appsercet = $this -> weixin['appsercet'];
        $this -> appid = 'wx48440373f9573421';
        $this -> appsercet = '2f72a15be37964c5a3fac2f23511f52e';

        $this -> code = $request -> param('code');
        $this -> sessionKey = $request -> param('session_key');
        $this -> openId = $request -> param('openid');
        $this -> encryptedData = input('param.encryptedData');
        $this -> iv = input('param.iv');
    }

//    public function tosissionkey(){
//
////        $code = input('param.code');
////        $encryptedData = input('param.encryptedData');
////        $iv = input('param.iv');
//////        dump($encryptedData);
////        if(empty($code)){
////            return json(['code' => 2,'msg'=>ReturnCode::$return_code[2]]);
////        }
//        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this -> appid.'&secret='.$this -> appsercet.'&js_code='.$this -> code.'&grant_type=authorization_code';
//        dump($url);
//        $res = curl_get_https($url);
//        $useropen = json_decode($res,JSON_UNESCAPED_UNICODE);
////        dump($useropen);
//        if(!isset($useropen['session_key'])){
////            return json(['code'=>0,'msg'=>ReturnCode::$return_code[0],'data'=>$useropen]);
//            return json($useropen);
//        }
//
////        $info = $this->toinfo($useropen['session_key'],$encryptedData,$iv);
////        $info['session_key'] = $useropen['session_key'];
////        dump($info);
//
//        //导出session_key
//        //添加用户数据
//
//        return json(['code'=>0,'msg'=>ReturnCode::$return_code[0],'data'=>$useropen]);
//
//    }
//
//    //解密
//    private function toinfo($sessionKey,$encryptedData,$iv){
//        $WXPhone = new WXBizDataCrypt($this -> appid, $sessionKey);
////        $data = null;
//        $errCode = $WXPhone->decryptData($encryptedData, $iv, $data);
//        $data = json_decode($data);
////        dump($data);
//        $info = object_array($data);
////        dump($info);
//        return $info;
//    }
//    //手机号
//    public function tophone(){
//        $sessionKey = input('param.session_key');
//        $encryptedData = input('param.encryptedData');
//        $iv = input('param.iv');
////        $code = input('param.code');
//
//
//        $info = $this->toinfo($sessionKey,$encryptedData,$iv);
//        dump($info);
//
//    }
    //无论是获取手机号 还是用户信息  -》   发送code  -> 服务器上换取openid + session_key     ->    换取所需的

    private function login($code){
//        $code = input('param.code');
//        dump($encryptedData);
//        if(empty($code)){
//            return json(['code' => 2,'msg'=>ReturnCode::$return_code[2]]);
//        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='. $this -> appid.'&secret='.$this -> appsercet.'&js_code='.$code.'&grant_type=authorization_code';
//        return $url;
        $res = curl_get_https($url);
        $useropen = json_decode($res,JSON_UNESCAPED_UNICODE);
        if (array_key_exists('session_key',$useropen) !== false){
            $has = User::where('openid','=', $useropen['openid'])->find();

            if(!$has){
                $useropen['share_id'] = uuid();
                User::create($useropen)->allowField(true);
            }else{
                $useropen['share_id'] = $has['share_id'];
            }
//            $hasbag = UserShop::where('openid','=',$useropen['openid'])->find();
//            if(!$hasbag){
//                $useropen['shopping'] ='[]';
//                UserShop::create($useropen)->allowField(true);
//            }
        }

        return $useropen;
//        if(!isset($useropen['session_key'])){
////            return json(['code'=>0,'msg'=>ReturnCode::$return_code[0],'data'=>$useropen]);
//            return json(['code'=>5,'msg'=>ReturnCode::$return_code[5],'data'=>$useropen]);
//        }
//        return json(['code'=> 0,'msg'=>ReturnCode::$return_code[0],'data'=>$useropen]);
    }

    private function toinfo($sessionKey, $encryptedData, $iv)
    {
        $WXPhone = new WXBizDataCrypt($this->appid, $sessionKey);
    //        $data = null;
        $errCode = $WXPhone->decryptData($encryptedData, $iv, $data);
        $data = json_decode($data);
    //        dump($data);
        $info = object_array($data);
//            halt($info);
        return $info;
    }

    public function userinfo(){
        if(empty($this -> encryptedData) || empty($this -> iv)){
            return json(['code'=>2,'msg'=>ReturnCode::$return_code[2]]);
        }
        if(empty($this -> sessionKey)){
            $loginData = $this->login($this -> code);
            if(!$loginData){
                return json(['code'=>1,'msg'=>ReturnCode::$return_code[1]]);
            }
            if(array_key_exists('session_key',$loginData) === false){
                if($loginData['errcode'] == '40163'){
                    return json(['code'=>16,'msg'=>ReturnCode::$return_code[16],'data'=>$loginData]);
                }
                return json(['code'=>10,'msg'=>ReturnCode::$return_code[10],'data'=>$loginData]);
            }
            $this -> sessionKey = $loginData['session_key'];
            $this -> openId = $loginData['openid'];
        }
        if(empty($this -> openId)){
            return json(['code'=>2,'msg'=>ReturnCode::$return_code[2]]);
        }
        $data = $this ->toinfo($this ->sessionKey,$this -> encryptedData , $this -> iv);

        if($data){
            $where = ['openid' => $this -> openId];
//            dump(array_key_exists('purePhoneNumber',$data));
//            die;
            if(array_key_exists('purePhoneNumber',$data) !== false){
                $userInfo = ['phone' => $data['purePhoneNumber']];
            }else{
                $userInfo = [
                    'uname'=>$data['nickName'],
                    'sex'=>$data['gender'],
                    'uimg'=>$data['avatarUrl'],
                ];
//                dump($userInfo);
////                die();
            }
            User::update($userInfo,$where)->allowField(true);
            $info =User::where($where)->find();
            if($info){
                return json(['code'=>0,'msg'=>ReturnCode::$return_code[0],'data'=>['session_key'=>$this->sessionKey,'openid'=>$this->openId,'share_id' => $info['share_id']]]);
            }
            return json(['code'=>1,'msg'=>ReturnCode::$return_code[1]]);
        }
        return json(['code'=>5,'msg'=>ReturnCode::$return_code[5]]);
    }

    //登录
    public function dologin(){
        if(empty($this -> code)){
            return json(['code' =>2 , 'msg'=>ReturnCode::$return_code[2]]);
        }
        $res = $this->login($this -> code);
        if(array_key_exists('session_key',$res) === false){
            if($res['errcode'] == '40163'){
                return json(['code'=>16,'msg'=>ReturnCode::$return_code[16],'data'=>$res]);
            }
            return json(['code'=>10,'msg'=>ReturnCode::$return_code[10],'data'=>$res]);
        }
        if($res){
            return json(['code'=>0,'msg'=>ReturnCode::$return_code[0],'data'=>$res]);
        }
        return json(['code' => 1,'msg'=>ReturnCode::$return_code[1]]);
    }

    //店信息
    public function storeinfo(){
        $res = db('admin')->field('shopName,shopPhone,shopAddress,shopLon,shopLat')->find();
        if($res){
            return json(['code'=>0,'msg'=>ReturnCode::$return_code[0],'data'=>$res]);
        }
        return json(['code'=>5,'msg'=>ReturnCode::$return_code[5]]);
    }
    //优惠券
    //1, 生成uuid -》 uuid -》 该优惠券表  uuid  折扣 使用规则 有效期限 删除-》添加领取表 -》 有就不能再领 -》 使用字段 openid  uuid  领取时间  使用时间
    //分享
    //  1，通过url 判断连接入口  带 用户uuid就是通过分享进入的，带有优惠（后台设定）
    //  2，查询出有多少人通过分享连接进入   自己会折扣多少（后台设定），
}